<template>
  <div style="margin-top: 10px">
    <a-tree
      v-if="showTree"
      v-model:selectedKeys="selectedKeys"
      :tree-data="treeData"
      draggable
      show-icon
      defaultExpandAll
      @select="onSelect"
      @dragend="onDragend"
      @drop="onDrop"
      @dblclick="onDoubleClick"
    >
      <template #switcherIcon="{ switcherCls }">
        <down-outlined :class="switcherCls" />
      </template>
      <template #icon="{ type, state }">
        <template v-if="type === 'system'">
          <template v-if="state === 'active'">
            <appstore-add-outlined />
          </template>
          <template v-else>
            <appstore-add-outlined style="color: red" />
          </template>
        </template>
        <template v-else>
          <template v-if="state === 'active'">
            <database-outlined />
          </template>
          <template v-else>
            <database-outlined style="color: red" />
          </template>
        </template>
      </template>
    </a-tree>
  </div>
</template>

<script setup>
  import { DownOutlined, DatabaseOutlined, AppstoreAddOutlined } from '@ant-design/icons-vue'
  import { Tree as ATree } from 'ant-design-vue'
  import { onMounted, ref, onBeforeMount } from 'vue'
  import { useRouter } from 'vue-router'
  import bus from 'vue3-eventbus'
  import { getDescendants } from '/@/api/module/module'
  import { useModuleStoreWithOut } from '/@/store/modules/module'

  const store = useModuleStoreWithOut()
  const router = useRouter()
  const selectedKeys = ref([])
  const treeData = ref([])
  const showTree = ref(false)

  onBeforeMount(() => {
    if (store.getRoot.id === 0 || store.getRoot.name === 'none') {
      router.push('/module/index')
    }
  })

  onMounted(() => {
    bus.on('refreshTree', () => {
      loadTreeData()
    })
    loadTreeData()
  })

  function loadTreeData() {
    treeData.value = [] // clear data first

    if (store.getRoot.id != 0) {
      getDescendants({ root: store.getRoot.id })
        .then((data) => {
          console.log('### parent:', data)
          let node = {
            title: data.parent.name,
            key: data.parent.name,
            id: data.parent.moduleId,
            type: data.parent.moduleType,
            desc: data.parent.desc,
            parentId: data.parent.parentId,
            state: data.parent.activeState,
            children: [],
          }
          makeTreeData(node, data.descendants)
          treeData.value.push(node)
          setSelectedKeys()
          // 数据加载完后再显示，否则可能 defaultExpandAll 不生效
          showTree.value = true
        })
        .catch((e) => {
          console.error('get module list failed:', e)
        })
    }
  }

  function makeTreeData(node, modules) {
    if (!modules || !node) return

    // find children
    for (let mod of modules) {
      if (mod.parentName === node.key) {
        console.log('### parent:', mod)
        let child = {
          title: mod.name,
          key: mod.name,
          id: mod.moduleId,
          state: mod.activeState,
          type: mod.moduleType,
          desc: mod.desc,
          parentId: mod.parentId,
          children: [],
        }
        node.children.push(child)
      }
    }

    // make children
    for (let child of node.children) {
      makeTreeData(child, modules)
    }
  }

  function setSelectedKeys() {
    selectedKeys.value = []
    selectedKeys.value.push(store.getParent.name)
  }

  function onSelect(selectedKeys, e) {
    console.log('### parent:', e)
    store.setParent({
      id: e.node.id,
      name: e.node.key,
      desc: e.node.desc,
      app: e.node.app,
      space: e.node.space,
      type: e.node.type,
      parent: e.node.parentId,
    })
  }

  function onDragend(e) {
    console.log('onDragEnd', e)
  }

  function onDrop(e) {
    console.log('onDrop', e)
  }

  function onDoubleClick(e, data) {
    if (data.id === store.getRoot.id) {
      loadTreeData()
    }
  }
</script>
